#pragma once
#include "Common.hpp"
using namespace LOGSpace;
class TcpServer
{
private:
    struct ThreadData
    {
        int _sockfd;
        TcpServer *_self;
        InetAddr _addr;
        ThreadData(int sockfd, TcpServer *self, const InetAddr &addr)
            : _sockfd(sockfd),
              _self(self),
              _addr(addr)
        {}
    };

public:
    TcpServer(uint16_t port = gPORT, int listen_sockfd = gSOCKFD_DEFAULT) : _port(port), _listen_sockfd(listen_sockfd)
    {
    }
    ~TcpServer()
    {
    }
    void InitServer()
    {
        // 创建套接字socket
        _listen_sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sockfd < 0)
        {
            LOG(FATAL, "sokfd error!\n");
            exit(SOCKED_ERROR);
        }
        LOG(INFO, "sockfd create suceess!,sokfd = %d\n", _listen_sockfd);
        // bind ip && port
        struct sockaddr_in peer;
        memset(&peer, 9, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_addr.s_addr = INADDR_ANY;
        peer.sin_port = htons(_port);
        if (::bind(_listen_sockfd, (struct sockaddr *)&peer, sizeof(peer)) < 0)
        {
            LOG(FATAL, "bind error!\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success!\n");
        // 监听连接请求
        if (::listen(_listen_sockfd, gblock) < 0)
        {
            LOG(FATAL, "listen error!\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen succss!\n");
    }
    void Start()
    {
        _isrunnung = true;
        while (_isrunnung)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // accept连接
            int sockfd = ::accept(_listen_sockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                // accept失败不需要退出服务器,重新连接即可
                LOG(WARNING, "ACCEPT ERROR!\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO, "Get a new link,mssage = %s\n", addr.GetAddrStr().c_str());
            // 业务TODO---多线程
            ThreadData* td = new ThreadData(sockfd,this,addr);
            pthread_t tid;
            pthread_create(&tid, nullptr, handler, td);
        }
        _isrunnung = false;
    }
    static void *handler(void *args)
    {
        pthread_detach(pthread_self());//分离线程
        ThreadData* td = static_cast<ThreadData*>(args);

        td->_self->Server(td->_sockfd,td->_addr);
        
        return nullptr;
    }
    void Server(int sockfd, InetAddr addr)
    {
        while (_isrunnung)
        {
            // 收client发送的信息==read数据
            char inbuf[1024];
            ssize_t n = read(sockfd, inbuf, sizeof(inbuf) - 1);
            if (n > 0)
            {
                // 接收消息成功
                inbuf[n] = 0;
                std::cout << "Receve [" << addr.GetAddrStr().c_str() << "] sended msg = " << inbuf << std::endl;
                std::string echo_msg = "[server echo]# ";
                echo_msg += inbuf;
                write(sockfd, echo_msg.c_str(), echo_msg.size());
            }
            else if (n == 0)
            {
                // client quit
                LOG(INFO, "client[%s] quit\n", addr.GetAddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read [%s] message error!\n", addr.GetAddrStr().c_str());
                break;
            }
        }
        ::close(sockfd);
    }

private:
    int _listen_sockfd; // socket描述符
    uint16_t _port;     // 端口号
    bool _isrunnung = false;
};